import logging
import random

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from celery_tasks.sms.tasks import send_sms_code
from verifications import constants

logger = logging.getLogger('django')


class SMSCodeView(APIView):
    """
    发送短信
    """
    def get(self, request, mobile):
        # 1.获取redis的链接对象
        redis = get_redis_connection('verify')
        # 2.发送短信之前，判断是否60s内发送过短信
        sms_flag = redis.get('sms_flag_%s' % mobile)
        if sms_flag:
            # sms_flag为True 则表示60s内发送过短信
            return Response({'message': "发送短信过于频繁"}, status=status.HTTP_400_BAD_REQUEST)
        # 3.生成和发送短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        try:
            # 发送短信 的异步任务必须通过delay调用
            send_sms_code.delay(mobile, sms_code)
        except Exception as e:
            # 发送短信失败，记录错误到日志中
            logger.error('发送短信失败！%s ； %s'% (mobile, sms_code))
            return Response({'message': '发送短信失败！'}, status=status.HTTP_502_BAD_GATEWAY)
        # 4. 保存短信验证码【保存到redis中】
        pl = redis.pipeline()  # 创建管道对象，管道对象具有和redis链接对象一样的操作方法，区别在于不会立即提交
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_DEXPIRES, sms_code)
        pl.setex('sms_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()  # 同意提交redis操作，提高性能

        return Response({'message': 'OK'})